package cn.com.hatech.cdkey.common.interceptor;

import cn.com.hatech.cdkey.common.constant.Types;
import cn.com.hatech.cdkey.common.constant.WebConst;
import cn.com.hatech.cdkey.common.utils.*;
import cn.com.hatech.cdkey.module.index.entity.User;
import cn.com.hatech.cdkey.module.index.service.IUserService;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.common.exception
 * @className: TipException
 * @author: xuruikai
 * @description: 自定义基础拦截器
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@Component
@Slf4j
public class BaseInterceptor implements HandlerInterceptor {

    private static final String USER_AGENT = "user-agent";

    @Resource
    private IUserService userService;

    private MapCache cache = MapCache.single();

    @Resource
    private Commons commons;

    @Resource
    private BasePageUtils basePageUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();

        log.info("UserAgent: {}", request.getHeader(USER_AGENT));
        log.info("用户访问地址: {}, 来路地址: {}", uri, IpUtils.getIpAddrByRequest(request));

        //请求拦截处理
        User user = TaleUtils.getLoginUser(request);
        if (null == user) {
            Integer uid = TaleUtils.getCookieUid(request);
            if (null != uid) {
                //这里还是有安全隐患,cookie是可以伪造的
                user = userService.queryUserById(uid);
                request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
            }
        }
        if (uri.startsWith(WebConst.ADMIN_URL) && !uri.startsWith(WebConst.ADMIN_LOGIN_URL) && null == user) {
            // 当用户信息为空, 并且跳转后台管理路径(/**)的情况下, 转发到后台登录页面
            response.sendRedirect(request.getContextPath() + WebConst.ADMIN_LOGIN_URL);
            return false;
        }
        //设置get请求的token
        if (WebConst.GET.equals(request.getMethod())) {
            String csrfToken = IdUtil.randomUUID();
            // 默认存储30分钟
            cache.hset(Types.CSRF_TOKEN.getType(), csrfToken, uri, 30 * 60);
            // 存储至token中
            request.setAttribute(WebConst.TOKEN_KEY, csrfToken);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
        //一些工具类和公共方法 添加后可在页面直接使用
        httpServletRequest.setAttribute("commons", commons);
        httpServletRequest.setAttribute("basePageUtils", basePageUtils);
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
